package client.material.button;

import client.common.dto.MaterialUpdateDTO;
import client.common.result.Result;
import client.material.MaterialArchiveQuery;
import client.material.MaterialEditDialog;
import remote.service.MaterialService;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ButtonEditor extends AbstractCellEditor implements TableCellEditor, ActionListener {
    
    private JButton button;
    private JTable table;
    private int row;
    private boolean isEdit; // 代表是否是修改操作
    private MaterialService materialService = new MaterialService() {
    }; // 使用物料服务
    
    public ButtonEditor(JTable table, boolean isEdit) {
        this.table = table;
        this.isEdit = isEdit;
        button = new JButton(isEdit ? "修改" : "删除");
        button.addActionListener(this);
    }
    
    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        this.row = row;
        button.setText(isEdit ? "修改" : "删除"); // 更新按钮文本
        return button;
    }
    
    @Override
    public Object getCellEditorValue() {
        return isEdit ? "修改" : "删除";
    }
    
    @Override
    public void actionPerformed(ActionEvent e) {
        fireEditingStopped(); // 停止编辑
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        Long materialId = (Long) model.getValueAt(row, 0);
        
        if (isEdit) {
            // 获取当前行的其他数据
            Long id = (Long) model.getValueAt(row, 0);
            String materialName = (String) model.getValueAt(row, 1);
            String specification = (String) model.getValueAt(row, 2);
            Long stock = (Long) model.getValueAt(row, 3);
            String unit = (String) model.getValueAt(row, 4);
            String remark = (String) model.getValueAt(row, 5);
            handleEdit(id, materialName, specification, stock, unit, remark);
        } else {
            handleDelete(materialId); // 直接使用 Long 类型的 id
        }
    }
    
    private void handleEdit(Long id, String materialName, String specification, Long stock, String unit, String remark) {
        MaterialEditDialog editDialog = new MaterialEditDialog(id, materialName, specification, stock, unit, remark);
        editDialog.setVisible(true);
        
        if (editDialog.isConfirmed()) {
            MaterialUpdateDTO materialUpdateDTO = MaterialUpdateDTO.builder()
                    .id(id)
                    .name(editDialog.getMaterialName())
                    .specification(editDialog.getSpecification())
                    .stock(editDialog.getStock())
                    .unit(editDialog.getUnit())
                    .remark(editDialog.getRemark())
                    .build();
            
            try {
                Result result = materialService.updateMaterial(materialUpdateDTO);
                if (result != null && result.isSuccess()) {
                    JOptionPane.showMessageDialog(table, "修改成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                    refreshTable();
                } else {
                    JOptionPane.showMessageDialog(table, "修改失败！", "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(table, "网络错误，请重试！", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
    
    private void handleDelete(Long id) {
        int confirmed = JOptionPane.showConfirmDialog(table, "确认要删除该物料吗？", "确认删除", JOptionPane.YES_NO_OPTION);
        if (confirmed == JOptionPane.YES_OPTION) {
            try {
                Result result = materialService.deleteMaterialById(id); // 使用物料ID进行删除
                if (result != null && result.isSuccess()) {
                    JOptionPane.showMessageDialog(table, "删除成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                    ((DefaultTableModel) table.getModel()).removeRow(row); // 从表格中移除行
                    refreshTable(); // 刷新表格以更新数据
                } else {
                    JOptionPane.showMessageDialog(table, "删除失败！", "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(table, "网络错误，请重试！", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
    
    private void refreshTable() {
        ((MaterialArchiveQuery) SwingUtilities.getWindowAncestor(table)).freshTable(); // 刷新表格
    }
}
